﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription.OP080;

using Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


using ZR.Model.Models.ProductionControl;
using ZR.Model.System;
using ZR.Service.IService.ProductionControl;
using ZR.ServiceCore.Services;

namespace CKS.PLC.Action.Subscription.OP80
{
    /// <summary>
    /// 动作编号5
    /// 实时采集-炉子温度
    /// </summary>
    public class DB1200_Work05Action : PLCAction
    {
        private  ICksConfigService sysConfigService;

        public DB1200_Work05Action(DecodeValue _value) : base(_value)
        {
            sysConfigService = serviceProvider.GetRequiredService<ICksConfigService>();
        }
        public override void Execute()
        {
            
            var result = Value.Value.ToInt();

            var degree1 =Value.GetLinkData(1).ToDecimal();
            var degree2 = Value.GetLinkData(2).ToDecimal();

            //判断上次采集时间与当前时间的时间差。
            //从数据库查询最后采集时间
            //从数据库获取采集间隔
            CksConfig internalConfig = sysConfigService.GetSysConfigByKey("sys.furnace.internal");

            if(InternalApp.LastOP90RealtimeCollectionTime == App.MinTime)
            {
                InternalApp.LastOP90RealtimeCollectionTime = DateTime.Now;
            }

            var ts = DateTime.Now - InternalApp.LastOP90RealtimeCollectionTime;
            if(ts.TotalSeconds+0.05 > internalConfig.ConfigValue.ToDouble() )
            {
                InternalApp.LastOP90RealtimeCollectionTime = DateTime.Now;
                //保存采集的温度信息
                //推送炉温给UI，绘制实时曲线
                var model = db.Queryable<CksHeatTreatment>().OrderByDescending(a => a.Id).First();
                if (model != null && model.Status == 1)
                {
                    //当前正在加热产品，保存此温度信息 CksHeatTreatmentDetails
                    
                        SaveDetails(degree1, model.BatchNo,1,model.ShelfCode1);
                        SaveDetails(degree2, model.BatchNo, 2,model.ShelfCode2);

                }

                //将温度信息推送到实时曲线
                var job = InternalApp.JobProvider.GetService<PushJob>();
                job.AddDegree(degree1,degree2);
                
            }
        }

        private  void SaveDetails(decimal degree1, string batchno,int location,int shelfcode)
        {
            var model_d = new CksHeatTreatmentDetails()
            {
                BatchNo = batchno,
                Degree = degree1,
                CreatedTime = DateTime.Now,
                Location = location,
                ShelfCode = shelfcode,
            };
            db.Insertable(model_d).ExecuteCommand();
        }
    }
}
